package com.seek.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.seek.servicebase.exceptionhandler.SeekException;
import com.seek.vod.service.VodService;
import com.seek.vod.utils.ConstantPropertiesUtil;
import com.seek.vod.utils.VodUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author: wml
 * @since: 2022/2/3 18:47
 */
@Service
public class VodServiceImpl implements VodService {
    // 上传视频到阿里云，返回视频 id
    @Override
    public String uploadAlyVideo(MultipartFile file) {
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String fileName = file.getOriginalFilename();
        String title = fileName.substring(0, fileName.lastIndexOf("."));
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadStreamResponse response = uploader.uploadStream(request);
        return response.getVideoId();
    }

    // 根据视频 id 删除阿里云中的视频，同时修改小节中的视频 id 和视频名称
    @Override
    public void removeAlyVideoByVideoId(String videoIds) {
        DefaultAcsClient client = VodUtil.initVodClient();
        DeleteVideoResponse response = new DeleteVideoResponse();
        try {
            response = VodUtil.deleteVideo(client, videoIds);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SeekException(20001, "删除视频失败，请稍后重试");
        }
    }
}
